C - Pass an array to a function

chris (2008-10-31 08:33:08)
2173 views
1 replies
It's ages since I did any c programming, but when I heard somebody the other day saying that you can't pass an array to a function, that sounded pretty unlikely, so I wrote this on the bus this morning just to prove the point:

#include <stdio.h>

/* pass an array to a function */

void display(int arr[]);

int main(int argc, char* argv[]){
	int numbers[3]; 

	numbers[0] = 23;
	numbers[1] = 43;
	numbers[2] = 36;
	display(numbers);

	return 0;
}

void display(int arr[]){
	printf("\nvalue 1 is %d\n",arr[0]);
	printf("\nvalue 2 is %d\n",arr[1]);
	printf("\nvalue 3 is %d\n",arr[2]);
}

Compiling and running the program gives the following output:

secondhalf-lm:junk clacy$ gcc array.c -o array && ./array

value 1 is 23

value 2 is 43

value 3 is 36



christo
comment
chris
2008-11-07 08:07:34

use malloc to allocate memory

Note, you can alternatively use malloc() to specify the size of you array. Calling malloc will allocate enough memory to accomodate the size of (in this case) an integer multiplied by 3. The benefit of using malloc is that it puts you in control of the reserved memory, allowing you to reallocate memory dynamically should you need to, and of course to free up memory which is no longer required. The end result should be more secure, less resource-hungry code. This is an inane example. I'm an inane kinda guy :)

#include <stdio.h>
#include <stdlib.h>

/* pass an array to a function */

void display(int arr[]);

int main(int argc, char* argv[]){
	int *numbers;

	numbers = malloc(sizeof(int)*3);

	numbers[0] = 23;
	numbers[1] = 43;
	numbers[2] = 36;
	display(numbers);

	free(numbers);
	return 0;
}

void display(int arr[]){
	printf("\nvalue 1 is %d\n",arr[0]);
	printf("\nvalue 2 is %d\n",arr[1]);
	printf("\nvalue 3 is %d\n",arr[2]);
}


christo
reply icon